#include "cocos2d.h"
#include "cocos-ext.h"
#include "ParallaxList.h"
#include "Tree.h"

USING_NS_CC;
USING_NS_CC_EXT;

ParallaxList * ParallaxList::create(Monkey * monkey)
{
	ParallaxList *pList = new ParallaxList();
    if (pList && pList->init(monkey))
    {
        pList->autorelease();
        return pList;
    }
    else
    {
        CC_SAFE_DELETE(pList);
        return NULL;
    }
}
bool ParallaxList::init(Monkey * monkey)
{
	//CocosDenshion::SimpleAudioEngine::sharedEngine()->preloadEffect(SoundPoint);

	visibleSize = CCDirector::sharedDirector()->getVisibleSize();
	sizeX = 0;
	rapduoi = 0;
	//CCNode *pipe = createPips();
	this->trees = CCArray::createWithCapacity(TREE_COUNT);
    this->trees->retain();
	//this->addChild(pipe);
		// Tao ra 1 mang cac dam may
	this->clouds = CCArray::createWithCapacity(CLOUD_COUNT);
    this->clouds->retain();

	//this->backGrounds = CCArray::createWithCapacity(2);
	//this->backGrounds->retain();

	//bg1 = new Background();
	//bg2 = new Background();
	fCreateTrees();

	// Bind player dich de check va cham
	fBindPlayer(monkey);

	// Xac dinh cay ma con khi se treo dau tien -> ngau nhien
	srand( time(NULL)*500);
	int pPos = CCRANDOM_0_1() * TREE_COUNT; //[0,5] CCRANDOM_0_1() Value range[0,1]
	mCurrentTree = pPos;
	CCLog("So ngau nhien = %d",pPos);

	// Get tree Object from CCArray()
	CCObject *obj  = trees->objectAtIndex(pPos);

	Tree *atree = (Tree*)obj;
	
	// Set isChoose = true;
	atree->fSetIsChoose(true);

	float treeRightX = atree->fGetRightX();
	float treeLeftX = atree->fGetLeftX();

	// Di chuyen man hinh den vi tri cua cay duoc Random()
	//fParallaxMoveTo(ccp(treeRightX,visibleSize.height/2));

    this->schedule(schedule_selector(Tree::update));
	return true;
}



void ParallaxList::fCreateTrees(){

	// Create parallax here
	_treeNode = CCParallaxNodeExtras::node(); // Node quan ly tat ca cac cay
	_cloudNode = CCParallaxNodeExtras::node(); // Node quan ly tat ca cac dam may
	//_backgroundNode = CCParallaxNodeExtras::node(); // Node quan ly tat ca cac anh nen

	// khoi tao voi do uu tien nhu sau Cay > Dam may > Anh nen
    this->addChild(_treeNode,1);
	this->addChild(_cloudNode,0);
	//this->addChild(_backgroundNode,-1);

	int pPos = CCRANDOM_0_1() * 5;

	// Khoi tao cac cay
	CCPoint dustSpeed = ccp(0.2, 0.2);
	for (int i = 0; i < TREE_COUNT; i++) {
		
		CCLog("Lan thu %d",i);
		Tree *tree =new  Tree();
		//tree->setScale(0.5f);
		tree->fSetIsChoose(false); // Set is choose
		//tree->setAnchorPoint(ccp(0, 1));

		sizeX += i*100;
		_treeNode->addChild(tree, 1, dustSpeed,ccp(200+(i+pPos)*100,-tree->getContentSize().height/2) ); // 2
		this->trees->addObject(tree);  //  retains bullet

    }

	// Khoi tao cac dam may
	CCPoint cloudSpeed = ccp(0.09, 0.09); 
	for(int i=0;i< CLOUD_COUNT;i++)
	{
		CCLog("Lan thu %d",i+1);
		Cloud *cloud = new Cloud();
		_cloudNode->addChild(cloud, 1, cloudSpeed,ccp(100+ i*100,200 + i*50) ); // 2
		clouds->addObject(cloud);  // add a cloud to Cloud Node
	}


	// Khoi tao anh nen
	//CCPoint backgroundSpeed = ccp(0.2, 0.2); 
	//_backgroundNode->addChild(bg1, 1, backgroundSpeed,ccp(0,visibleSize.height/2) ); // 2
 //   _backgroundNode->addChild(bg2,1, backgroundSpeed, ccp( bg2->getContentSize().width,visibleSize.height/2));

	//backGrounds->addObject(bg1);
	//backGrounds->addObject(bg2);

}

// Ham tra ve mang quan ly tat ca cac cay
CCArray * ParallaxList::fGetTrees()
{
	return this->trees;
}

/*
	Dang can nhac, neu thua thi se xoa neu can

*/
void ParallaxList::fCheckMovePass() {

	CCObject *obj;
	CCARRAY_FOREACH(this->trees, obj){
		Tree *singleTree = (Tree *)obj;

		if (singleTree->getTag() == TREE_NEW) 
		{
			if(this->mMonkey->getPositionX() > singleTree->getPositionX())
			{
					singleTree->setTag(TREE_PASS);
			}
		}
	}
}
/*
	Dang can nhac, neu thua thi se xoa neu can
	
*/
void ParallaxList::fRenewTree()
{
	CCObject *obj;
	CCARRAY_FOREACH(this->trees, obj)
	{

		Tree *singleTree = (Tree *)obj;
        singleTree->setPositionX(singleTree->getPositionX() - 2);
        if(singleTree->getPositionY() > visibleSize.height) {
            singleTree->setTag(TREE_NEW);
        }
    }
}

// Ham di chuyen cua so Game toi vi tri mong muon
void ParallaxList::fParallaxMoveTo(CCPoint p)
{

	CCActionInterval* goTo = CCMoveBy::create(1.5f,p);
	CCSequence* seq = CCSequence::create(goTo, NULL);
    _treeNode->runAction(seq);

	/*CCActionInterval* goTo2 = CCMoveBy::create(1.5f,p);
	CCSequence* seq2 = CCSequence::create(goTo, NULL);
	_cloudNode->runAction(seq2);*/

	CCLog("Thuc hien di chuyen !!!!!!!!!!!!!!!!!!!!!!");

	//CCActionInterval* goTo3 = CCMoveBy::create(1.5f,p);
	//CCSequence* seq3 = CCSequence::create(goTo, NULL);
	//_backgroundNode->runAction(seq3);

	/*CCActionInterval* goUp = CCMoveBy::create(1.5f, ccp(1000,0) );
    CCActionInterval* goDown = goUp->reverse();

	CCSequence* seq = CCSequence::create(goUp, goDown, NULL);
    _treeNode->runAction( (CCRepeatForever::create(seq) ));*/

}
void ParallaxList::update(float dt){
	/*
		CAC HAM KIEM TRA
	*/
	//CCLog("Update pipe position");
	// Check Hit here
	//this->fCheckMovePass();
	// Change position


	/*
		Neu cay di chuyen vuot qua kich thuoc man hinh
		Cap nhat lai vi tri cho cay
	*/
	CCPoint backgroundScrollVert = ccp(0,  visibleSize.height);
	_treeNode->setPosition(ccpAdd(_treeNode->getPosition(), ccpMult(backgroundScrollVert, dt)));
	
	for (int ii=0; ii< trees->count(); ii++) {
        Tree* tree = (Tree *)(trees->objectAtIndex(ii));
        float yPosition = _treeNode->convertToWorldSpace(tree->getPosition()).y;
		float size = tree->getContentSize().height;
  //      if (yPosition > visibleSize.height + size/2) 
		//{
		//	//CCLog("yPosition = %f",yPosition);
		//	//CCLog("Set lai vi tri cho cay");
		//	int pPos = CCRANDOM_0_1() * 5;
		//	float y =  - visibleSize.height - size;
		//	_treeNode->incrementOffset(ccp(0,y), tree);
		//	chay = 0;
  //      }
		
		if (yPosition > -tree->mTopSide) 
		{
			tree->fAssemblyBodyTree();
			CCLOG("%f",tree->mTopSide);
        }
    }

	/*
		Neu dam may di chuyen vuot qua kich thuoc man hinh
		Cap nhat lai vi tri cho dam may
	*/
	CCPoint backgroundScrollVert2 = ccp(0,  visibleSize.height);
	_cloudNode->setPosition(ccpAdd(_cloudNode->getPosition(), ccpMult(backgroundScrollVert2, dt)));
	
	for (int ii=0; ii< clouds->count(); ii++) {
        CCSprite * xxx = (CCSprite *)(clouds->objectAtIndex(ii));
        float yPosition = _cloudNode->convertToWorldSpace(xxx->getPosition()).y;
		float size = xxx->getContentSize().height;
		//CCLog("Size cua dam may = %f",size);
        if (yPosition > visibleSize.height + size/2) {
			//CCLog("yPosition = %f",yPosition);
			//CCLog("Set lai vi tri cho DAM MAY");
			int pPos = CCRANDOM_0_1() * 5;
			float y =  - visibleSize.height - size/2 - pPos*100;
			_cloudNode->incrementOffset(ccp(0,y), xxx);
        }
    }


	/*
		Neu anh nen di chuyen vuot qua kich thuoc man hinh
		Cap nhat lai vi tri cho anh nen
	*/

	/*
	CCPoint backgroundScrollVert3 = ccp(0,  visibleSize.height);
	_backgroundNode->setPosition(ccpAdd(_backgroundNode->getPosition(), ccpMult(backgroundScrollVert3, dt)));
	
	for (int ii=0; ii< backGrounds->count(); ii++) {
        CCSprite * xxx = (CCSprite *)(backGrounds->objectAtIndex(ii));
        float yPosition = _backgroundNode->convertToWorldSpace(xxx->getPosition()).y;
		float size = xxx->getContentSize().height;
		//CCLog("Size cua dam may = %f",size);
        if (yPosition > visibleSize.height + size/2) {
			//CCLog("yPosition = %f",yPosition);
			//CCLog("Set lai vi tri cho DAM MAY");
			float y =  - visibleSize.height - size/2 - 100;
			_backgroundNode->incrementOffset(ccp(0,y), xxx);
        }
    }
	*/

	/*
	for ( int ii = 0; ii <backGrounds->count(); ii++ ) {
		CCSprite * background = (CCSprite *)(backGrounds->objectAtIndex(ii));
		float xPosition = _backgroundNode->convertToWorldSpace(background->getPosition()).x;
		float size = background->getContentSize().width;
		// Chu y cho nay
		if ( (xPosition < - size + 200)) {
			CCLog("X position = %f",xPosition);
			CCLog(" - Size +100 = %f",- size);
			CCLog("Chay sang trai");
			_backgroundNode->incrementOffset(ccp(960,0),background); // TH move ve phia trai
		}else if((xPosition > size  + 200) ){
			CCLog("X position = %f",xPosition);
			CCLog(" Size  - 100 = %f",size);
			CCLog("Chay sang phai");
			_backgroundNode->incrementOffset(ccp(-960,0),background); // TH move ve phia phai
		}
	}
	*/

}

void ParallaxList::fBindPlayer(Monkey * monkey)
{
	CCLog("Bind MONKEY TO PARALLAX NODE");
	// Bind vao 1 vi tri nao do
	this->mMonkey = monkey;
	this->mMonkey->setPositionX(0);// Monkey se bam vao vi tri ben phai cua than cay duoc Random()
	this->mMonkey->setPositionY(visibleSize.height/2);
	CCRect rect =  mMonkey->fGetArmature()->boundingBox();
	CCLOG("a");
}